package com.tourism.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tourism.admin.common.Result;
import com.tourism.admin.model.entity.Book;
import com.tourism.admin.mapper.BookMapper;
import com.tourism.admin.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController extends BaseController{

    @Autowired
    private BookService bookService;

    @PostMapping("/add")
    public Result<?> save(@RequestBody Book Book) {
        bookService.save(Book);
        return Result.success();
    }

    @PutMapping("/update")
    public Result<?> update(@RequestBody Book Book) {
        bookService.updateById(Book);
        return Result.success();
    }

    @DeleteMapping("delete/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        bookService.removeById(id);
        return Result.success();
    }

    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        bookService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(bookService.getById(id));
    }

    /**
     * 注意：这个方法使用的是Mybatis sql的方式做的多表联合查询，大家可以点开，参考下怎么写多表查询
     * @param userId
     * @return
     */
    @GetMapping("{userId}")
    public Result<?> getByUserId(@PathVariable Integer userId) {
        return Result.success(bookService.findByUserId(userId));
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "100") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Book::getName, search);
        }
        Page<Book> BookPage = bookService.page(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(BookPage);
    }
}
